<template>
  <view class="page">
    <!-- 头像区域 -->
    <view class="avatar-section">
      <CommonNavbar :showBack="true"></CommonNavbar>
      <view>
        <image class="avatar"
          :src="state.userInfo?.avatar ? IMAGE_URL + state.userInfo?.avatar : '/static/images/icon-avatar-default.png'"
          mode="aspectFill" @click="uploadFile"></image>
        <!-- <button
          class="update-btn"
          @click="uploadFile"
        >
          更换头像
        </button> -->
      </view>
      <!-- 身份信息区域 -->
      <view class="flex align-center" style="width: 100%">
        <view class="flex-sub padding-lr">
          <up-text color="#3D511D" size="12" :text="state.userInfo?.bio || '暂无签名'"></up-text>
        </view>
        <view class="padding-lr">
          <u-button shape="circle" size="mini" bgColor="transparent"
            customStyle="background:transparent;border:solid 1px #3D511D;color:#3D511D;width:80px !important;height:30px !important"
            @click="state.showEditBio = true">编辑签名</u-button>
        </view>
      </view>
    </view>
    <!-- 主要内容区域 -->
    <view class="main padding">
      <view class="bg-white radius padding">
        <up-cell-group :border="false">
          <up-cell title="昵称" :isLink="true" :value="state.userInfo?.nickName"
            @click="state.showEditNickname = true"></up-cell>
          <!-- <up-cell
          icon="integral-fill"
          title="会员等级"
          value="新版本"
        ></up-cell> -->
        </up-cell-group>
      </view>
      <!-- 编辑签名 -->
      <up-modal :showCancelButton="true" confirmColor="#6D9319" :show="state.showEditBio" @confirm="editBio"
        @cancel="state.showEditBio = false">
        <up-textarea v-model="state.newBio" placeholder="请输入内容" count></up-textarea>
      </up-modal>
      <!-- 编辑昵称 -->
      <up-modal :showCancelButton="true" confirmColor="#6D9319" :show="state.showEditNickname" @confirm="editNickname"
        @cancel="state.showEditNickname = false">
        <up-input v-model="state.newNickname" placeholder="请输入内容" count></up-input>
      </up-modal>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getUserInfoApi, updateBIOApi, updateAvatarApi, updateNicknameApi } from '@/api/me';
import { BASE_URL } from '@/utils/env.js';
import { IMAGE_URL } from '@/utils/env';

let fileList1 = ref([]);
const state = reactive({
  userInfo: {},
  showEditBio: false,
  showEditNickname: false,
  newBio: '', //新个性签名
  newNickname: '' //新个性签名
});
onLoad(() => {
  // state.userInfo = uni.getStorageSync('userInfo');
  getUserInfo();
});

const uploadFile = () => {
  uni.showLoading();
  uni.chooseImage({
    count: 1, // 默认9
    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: async (res) => {
      const tempFilePaths = res.tempFilePaths;
      try {
        console.log('try')
        uni.uploadFile({
          url: `${BASE_URL}/user/avatar`,
          filePath: tempFilePaths[0],
          name: 'avatarfile',
          header: {
            Authorization: uni.getStorageSync('token')
          },
          success: (res) => {
            console.log('res', res)
            uni.showToast({
              title: '上传成功',
              icon: 'none'
            });
            getUserInfo();
            uni.hideLoading()
          }
        });

        // const result = JSON.parse(uploadRes[0].data);
        // if (result.code === 200) {
        //   uni.showToast({
        //     title: '头像上传成功',
        //     icon: 'success'
        //   });
        //   getUserInfo();
        // } else {
        //   uni.showToast({
        //     title: result.msg || '上传失败',
        //     icon: 'none'
        //   });
        // }
      } catch (error) {
        console.log('catch')
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
        uni.hideLoading()
      } finally {
        console.log('finally')
        // uni.hideLoading();
      }
    }
  });
};

// return new Promise((resolve, reject) => {
//     let a = uni.uploadFile({
//       url: `${BASE_URL}/user/avatar`,
//       filePath: url,
//       name: 'avatarfile',
//       header: {
//         Authorization: uni.getStorageSync('token')
//       },
//       success: (res) => {
//         const result = JSON.parse(res.data);
//         getUserInfo();
//       }
//     });
//   });
// 获取用户信息
const getUserInfo = async () => {
  const result = await getUserInfoApi();
  if (result.code === 200) {
    state.userInfo = result.data;
    fileList1.value.push(IMAGE_URL + state.userInfo.avatar);
    console.log(IMAGE_URL + state.userInfo.avatar);
    // setUserInfo('userInfo', state.userInfo);
  }
};
// 编辑个性签名
const editBio = async () => {
  if (state.newBio == '') {
    uni.$u.toast('请输入内容');
    return;
  }

  const params = {
    bio: state.newBio
  };
  const result = await updateBIOApi(params);
  if (result.code === 200) {
    state.showEditBio = false;
    getUserInfo();
  } else {
    uni.$u.toast(result.msg);
    state.showEditBio = false;
  }
};
// 更新昵称
const editNickname = async () => {
  if (state.newNickname == '') {
    uni.$u.toast('请输入内容');
    return;
  }
  const params = {
    nickname: state.newNickname
  };
  const result = await updateNicknameApi(params);
  if (result.code === 200) {
    state.showEditNickname = false;
    getUserInfo();
  } else {
    uni.$u.toast(result.msg);
    state.showEditNickname = false;
  }
};
</script>

<style lang="scss" scoped>
.page {
  background-color: #f3f3f3;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  background: linear-gradient(97deg,
      rgba(212, 233, 162, 0.4) 0%,
      rgba(184, 211, 122, 0.32) 18.41%,
      rgba(210, 233, 158, 0.36) 42.07%,
      rgba(201, 236, 124, 0.36) 67.49%,
      rgba(233, 255, 184, 0.4) 85.9%);

  .avatar {
    width: 140rpx;
    height: 140rpx;
    border-radius: 50%;
    margin-bottom: 20rpx;
  }

  .update-btn {
    background: none;
    border: none;
    color: #666;
    font-size: 28rpx;
    padding: 0;
    line-height: 1.5;

    &::after {
      border: none;
    }
  }
}

.info-section {
  display: flex;
  align-items: center;
  border: solid 1px red;
  padding: 0 30px;
  width: 100%;

  .info-text {
    color: #333;
    font-size: 28rpx;
    flex: 1;
  }

  .edit-btn {
    width: 80px;
    height: 60rpx;
    font-size: 24rpx;
    background-color: transparent !important;
    color: #9cb95a;
  }
}
</style>
